import * as Apis from '../../apis/index'
import { base64Encode } from "../../utils/base64";
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
   orederCode:'',
   orderInfo:{},
   money:0,
   desc:'',
   token:''
  },
  toHome: function(){
    wx.navigateTo({
      url: '/pages/index/index',
    })
  },
  paySuccess:function(url){
    let cUrl = url || ''
    if(cUrl && String(cUrl).includes('?')){
      cUrl = encodeURIComponent(cUrl || '')
    }
    wx.redirectTo({
      url: `/pages/index/index${cUrl?'?url='+cUrl:''}`,
    })
  },
  goPay: async function () {
    const fData = this.data.orderInfo || {}
    const params = Object.assign({},fData)
    delete params.payMoney
    delete params.payDesc
    delete params.paySuccessUrl
    const {state,message,data:payRes} = await Apis.submitPayment(params)
    if (Number(state) !== 200) {
      app.showToast(message || '下单失败')
      return false
    }
    wx.requestPayment({
      timeStamp: payRes.timeStamp,
      nonceStr: payRes.nonceStr,
      package: payRes.package,
      signType: payRes.signType,
      paySign: payRes.paySign,
      success: () => { 
        app.showToast('支付成功')
        this.paySuccess(fData.paySuccessUrl)
      },
      fail: (res)=> {
        const message = String(res.errMsg).includes('fail cancel')?'取消支付':(res.errMsg || '支付失败')
        app.showToast(message)
       }
    })
  },
  async onLoad (options) {
    if(options.orederCode){
      const payInfo = app.globalData.payInfo || {}
      this.setData({
        orederCode:options.orederCode,
        orderInfo:payInfo[options.orederCode] || {}
      })
      await app.checkToken()
      this.goPay()
    }else{
      app.showToast('暂未拿到订单Id')
    }
  },
  onShareAppMessage: function () {
 
  }
})